#!/usr/bin/env node

import { spawn } from 'child_process';

// Test the delete branch functionality
function testDeleteBranch() {
  console.log('Testing Git Branch Delete functionality...\n');

  // Start the MCP server
  const server = spawn('node', ['dist/index.js'], {
    stdio: ['pipe', 'pipe', 'inherit']
  });

  const testMessages = [
    // Initialize connection
    {
      jsonrpc: '2.0',
      id: 1,
      method: 'initialize',
      params: {
        protocolVersion: '2024-11-05',
        capabilities: {},
        clientInfo: {
          name: 'test-client',
          version: '1.0.0'
        }
      }
    },
    // List branches before deletion
    {
      jsonrpc: '2.0',
      id: 2,
      method: 'tools/call',
      params: {
        name: 'list_branches',
        arguments: { type: 'local' }
      }
    },
    // Step 1: Delete local branch only
    {
      jsonrpc: '2.0',
      id: 3,
      method: 'tools/call',
      params: {
        name: 'delete_branch',
        arguments: {
          branchName: 'test-branch-for-delete',
          deleteRemote: false
        }
      }
    },
    // List branches after local deletion
    {
      jsonrpc: '2.0',
      id: 4,
      method: 'tools/call',
      params: {
        name: 'list_branches',
        arguments: { type: 'local' }
      }
    },
    // Try to delete the same branch again (should show error)
    {
      jsonrpc: '2.0',
      id: 5,
      method: 'tools/call',
      params: {
        name: 'delete_branch',
        arguments: {
          branchName: 'test-branch-for-delete',
          deleteRemote: false
        }
      }
    }
  ];

  let messageIndex = 0;

  server.stdout.on('data', (data) => {
    const responses = data.toString().trim().split('\n');
    responses.forEach(response => {
      if (response.trim()) {
        try {
          const parsed = JSON.parse(response);
          console.log(`Response to message ${parsed.id || '(notification)'}:`, JSON.stringify(parsed, null, 2));
          console.log('---');

          messageIndex++;
          if (messageIndex < testMessages.length) {
            console.log(`Sending message ${messageIndex + 1}:`, JSON.stringify(testMessages[messageIndex], null, 2));
            server.stdin.write(JSON.stringify(testMessages[messageIndex]) + '\n');
          } else {
            console.log('Delete branch test completed!');
            server.kill();
          }
        } catch (e) {
          console.log('Raw response:', response);
        }
      }
    });
  });

  server.on('error', (error) => {
    console.error('Server error:', error);
  });

  server.on('close', (code) => {
    console.log(`Server exited with code ${code}`);
  });

  // Send the first message
  console.log(`Sending message 1:`, JSON.stringify(testMessages[0], null, 2));
  server.stdin.write(JSON.stringify(testMessages[0]) + '\n');
}

testDeleteBranch();